package com.jilintongyi.jlcrtvu.reponsitory.impl;

import java.util.Iterator;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import com.jilintongyi.jlcrtvu.reponsitory.BaseRepository;

/**
 * 基础存储库实现类
 */
public class BaseRepositoryImpl<T, ID> extends SimpleJpaRepository<T, ID>
		implements BaseRepository<T, ID> {

	private final EntityManager em;
	private final int BATCH_SIZE = 100; // spring.jpa.properties.hibernate.jdbc.batch_size

	public BaseRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
		super(entityInformation, entityManager);
		this.em = entityManager;
	}

	public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
		super(domainClass, em);
		this.em = em;
	}

	@Override
	public <S extends T> Iterable<S> batchSave(Iterable<S> entitys) {
		Iterator<S> iterator = entitys.iterator();
		int index = 0;
		while (iterator.hasNext()) {
			em.persist(iterator.next());
			index++;
			if (index % BATCH_SIZE == 0) {
				em.flush();
				em.clear();
			}
		}
		if (index % BATCH_SIZE != 0) {
			em.flush();
			em.clear();
		}
		return entitys;
	}

	@Override
	public <S extends T> Iterable<S> batchUpdate(Iterable<S> entitys) {
		Iterator<S> iterator = entitys.iterator();
		int index = 0;
		while (iterator.hasNext()) {
			em.merge(iterator.next());
			index++;
			if (index % BATCH_SIZE == 0) {
				em.flush();
				em.clear();
			}
		}
		if (index % BATCH_SIZE != 0) {
			em.flush();
			em.clear();
		}
		return entitys;
	}
}
